﻿using Dapper;
using log4net;
using MySql.Data.MySqlClient;
using StoreProject.BLL.SettingBLL;
using StoreProject.BLL.StackBLL;
using StoreProject.DBUtil;
using StoreProject.Entity.SettingEntity;
using StoreProject.Entity.StackEntity;
using StoreProject.Enum;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySqlHelper = StoreProject.DBUtil.MySqlHelper;

namespace StoreProject.Forms.StackForms.Operate
{
    public partial class StackInSettingForm : Form
    {
        ILog _log = LogManager.GetLogger("StackInSettingForm");
        StackInEntity entity = null;
        ProductBLL productBLL = new ProductBLL();
        StackInBLL stackInBLL = new StackInBLL();
        StackLocationBLL stackLocationBLL = new StackLocationBLL();
        StackLogBLL stackLogBLL = new StackLogBLL();
        protected FormState _formState = FormState.INIT;
        public StackInSettingForm(FormState state)
        {
            InitializeComponent();
            _formState = state;
        }
        public StackInSettingForm()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid())
                return;
            OnSave();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void OnSave()
        {
            try
            {
                bool res = false;
                using (var Conn = MySqlHelper.getConnectionEx())
                {
                    MySqlTransaction trans = null;
                    try
                    {
                        Conn.Open();
                        trans = Conn.BeginTransaction();

                        StackInEntity model = GetModel();
                        var stackInEntitys = stackInBLL.GetListByWhere(string.Format("ProductName like '%{0}%'and StackLocation like '%{1}%'", this.cmbProductName.Text, this.cmbStackLocation.Text)).ToList();
                        //数据库里有对应的货品和库位
                        if (stackInEntitys != null && stackInEntitys.Count > 0)
                        {
                            var temp = stackInEntitys[0];

                            string sql = string.Format("select * from StackIn where id = '{0}' for update;", temp.Id);
                            var readStackInEntity = Conn.QueryFirstOrDefault<StackInEntity>(sql, trans, null, null);
                            if (readStackInEntity != null)
                            {
                                readStackInEntity.ProductCount = model.ProductCount + readStackInEntity.ProductCount;
                                string sql1 = string.Format("UPDATE StackIn set ProductCount = '{1}',StackLocation = '{2}',IsStack = true where Id = '{0}'", readStackInEntity.Id, readStackInEntity.ProductCount, readStackInEntity.StackLocation);
                                int flag = Conn.Execute(sql1, trans, null, null);
                                if (flag == 1)
                                {
                                    res = true;
                                    StackLogEntity stackLogEntity = new StackLogEntity();
                                    stackLogEntity.Id = Guid.NewGuid().ToString();
                                    stackLogEntity.StackOrderId = readStackInEntity.Id;
                                    stackLogEntity.StackLocation = readStackInEntity.StackLocation;
                                    stackLogEntity.LogType = "1";
                                    stackLogEntity.Note = "累加入库；货品：" + temp.ProductName + "；在库位" + temp.StackLocation + "上累加的数量为：" + temp.ProductCount;
                                    stackLogEntity.CreateTime = DateTime.Now;
                                    stackLogEntity.UpdateTime = DateTime.Now;
                                    stackLogBLL.Insert(stackLogEntity);
                                }
                                MessageBox.Show("入库成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                trans.Commit();
                            }
                            else
                                trans.Commit();
                        }
                        else
                        {
                            res = stackInBLL.Insert(model);
                            if (res)
                            {
                                StackLogEntity stackLogEntity = new StackLogEntity();
                                stackLogEntity.Id = Guid.NewGuid().ToString();
                                stackLogEntity.StackOrderId = model.Id;
                                stackLogEntity.StackLocation = model.StackLocation;
                                stackLogEntity.LogType = "0";
                                stackLogEntity.Note = "新增入库；货品：" + model.ProductName + "在该库位" + model.StackLocation + "新增数量为" + model.ProductCount;
                                stackLogEntity.CreateTime = DateTime.Now;
                                stackLogEntity.UpdateTime = DateTime.Now;
                                stackLogBLL.Insert(stackLogEntity);
                            }
                            if (res)
                            {
                                MessageBox.Show("入库成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.Close();
                            }
                            else
                            {
                                MessageBox.Show("入库失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback(); //回滚
                    }
                    finally
                    {
                        trans.Dispose(); //释放
                        Conn.Close();
                        this.Close();
                    }
                }
                #region 无事务处理
                //bool res = false;
                //if (_formState == FormState.ADD)
                //{
                //    StackInEntity model = GetModel();
                //    var stackInEntitys = stackInBLL.GetListByWhere(string.Format("ProductName like '%{0}%'and StackLocation like '%{1}%'", this.cmbProductName.Text, this.cmbStackLocation.Text)).ToList();
                //    if (stackInEntitys != null && stackInEntitys.Count > 0)
                //    {
                //        var temp = stackInEntitys[0];
                //        temp.ProductCount = model.ProductCount + temp.ProductCount;
                //        res = stackInBLL.Update(temp);
                //        if (res)
                //        {
                //            StackLogEntity stackLogEntity = new StackLogEntity();
                //            stackLogEntity.Id = Guid.NewGuid().ToString();
                //            stackLogEntity.StackOrderId = temp.Id;
                //            stackLogEntity.StackLocation = temp.StackLocation;
                //            stackLogEntity.LogType = "1";
                //            stackLogEntity.Note = "累加入库；货品：" + temp.ProductName + "；在库位"+ temp.StackLocation+ "上累加的数量为：" + temp.ProductCount;
                //            stackLogEntity.CreateTime = DateTime.Now;
                //            stackLogEntity.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity);
                //        }
                //    }
                //    else
                //    {
                //        res = stackInBLL.Insert(model);
                //        if (res)
                //        {
                //            StackLogEntity stackLogEntity = new StackLogEntity();
                //            stackLogEntity.Id = Guid.NewGuid().ToString();
                //            stackLogEntity.StackOrderId = model.Id;
                //            stackLogEntity.StackLocation = model.StackLocation;
                //            stackLogEntity.LogType = "0";
                //            stackLogEntity.Note = "新增入库；货品：" + model.ProductName + "在该库位"+ model.StackLocation+ "新增数量为" + model.ProductCount;
                //            stackLogEntity.CreateTime = DateTime.Now;
                //            stackLogEntity.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity);
                //        }
                //    }
                //}
                //else if (_formState == FormState.UPDATE)
                //{
                //    res = stackInBLL.Update(model);
                //}
                //if (res)
                //{
                //    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    this.Close();
                //}
                //else
                //{
                //    MessageBox.Show("保存失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}
                #endregion 
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                this.Close();
            }
        }

        private StackInEntity GetModel()
        {
            if (entity == null)
            {
                entity = new StackInEntity();
                entity.Id = Guid.NewGuid().ToString();
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = DateTime.Now;
            }
            else
            {
                entity.UpdateTime = DateTime.Now;
            }
            entity.ProductName = this.cmbProductName.Text;
            entity.ProductCode = this.cmbProductName.Text;
            entity.ProductCount = Convert.ToInt32(numProductCount.Value);
            entity.StackLocation = this.cmbStackLocation.Text;
            entity.UniPrice = this.numUniPrice.Value.ToString();
            entity.Type = this.cmbType.Text;
            entity.IsStack = true;
            return entity;
        }
        public bool IsValid()
        {
            errorProvider1.Clear();
            bool res = true;

            if (string.IsNullOrEmpty(txtProductCode.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtProductCode, "编码不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbProductName.Text))
            {
                res = false;
                errorProvider1.SetError(cmbProductName, "货品名称不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbStackLocation.Text))
            {
                res = false;
                errorProvider1.SetError(cmbStackLocation, "库位不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbStackLocation.Text))
            {
                res = false;
                errorProvider1.SetError(txtProductCode, "编码不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbType.Text))
            {
                res = false;
                errorProvider1.SetError(cmbType, "入库类型不能为空！");
            }
            return res;
        }

        private void StackInSettingForm_Load(object sender, EventArgs e)
        {
            InitData();
        }
        private void InitData()
        {
            if (_formState == FormState.ADD)
            {
                this.Text = "新增入库信息";
            }
            else if (_formState == FormState.UPDATE)
            {
                this.Text = "修改入库信息";
            }
            var list = productBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.ProductName).ToArray();
            this.cmbProductName.Items.AddRange(list);

            var list1 = stackLocationBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.StackName).ToArray();
            this.cmbStackLocation.Items.AddRange(list1);
            this.cmbType.SelectedIndex = 0;
        }

        private void cmbProductName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cmbProductName.Text))
            {
                var list = productBLL.GetListByWhere(string.Format("ProductName like '%{0}%'", this.cmbProductName.Text)).ToList();
                if (list == null || list.Count < 1)
                {
                    MessageBox.Show("该货品不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                var productEntity = list[0];
                this.txtProductCode.Text = productEntity.ProductCode;
            }
        }
    }
}
